import { useContext, useEffect, useRef } from "react";
import { echaresContext } from "../../context/index";
import ApiClient from "../../axios/index";
import "./index.less";
import { EChartsType } from "echarts";
const Trend = () => {
  const context = useContext(echaresContext);
  const trendRef = useRef<HTMLDivElement>(null);
  const allData = useRef(null);
  const trendEcharts = useRef<EChartsType | null>(null);
  const initEcharts = () => {
    trendEcharts.current = context.init(trendRef.current, "dark");
    const option = {
      xAxis: {
        type: "category",
        boundaryGap: false,
      },
      yAxis: {
        type: "value",
      },
      legend: {
        icon: "circle",
      },
      tooltip: {
        trigger: "axis",
      },
    };
    trendEcharts.current && trendEcharts.current.setOption(option);
  };
  const updateEcharts = () => {
    const mouth = allData.current && allData.current.common.month;
    const seriesArr =
      allData.current &&
      allData.current.map.data.map((item) => {
        return {
          name: item.name,
          type: "line",
          data: item.data,
          stack: "map",
          areaStyle: {},
        };
      });
    const option = {
      xAxis: {
        data: mouth,
      },
      series: seriesArr,
      legend: {
        data: seriesArr!.map((item) => item.name),
      },
    };
    // 更新数据
    trendEcharts.current && trendEcharts.current.setOption(option);
  };
  const screenResize = () => {
    const fontSize = (trendRef.current?.offsetWidth / 100) * 3.6;
    const option = {
      legend: {
        itemWidth: fontSize,
        itemHeight: fontSize,
        itemGap: fontSize,
        textStyle: {
          fontSize: fontSize / 2,
        },
      },
    };
    trendEcharts.current && trendEcharts.current.setOption(option);
  };
  const getData = () => {
    const apiClient = new ApiClient();
    apiClient.get("/trend").then((res) => {
      allData.current = res.data;
      updateEcharts();
    });
    // 获取数据
  };
  useEffect(() => {
    initEcharts();
    getData();
    window.addEventListener("resize", screenResize);
    screenResize();
    return () => {
      window.removeEventListener("resize", screenResize);
    };
  }, []);
  return <div className="trend-container" ref={trendRef}></div>;
};
export default Trend;
